import random
import re
from datetime import datetime

from . import register_blue
from flask import request, abort, current_app, make_response, Response, jsonify,session
from info.common import generate_captcha_image
from ... import sr, db

# 注册图片生成
from ...models import User
from ...response_code import RET, error_map


# 1.验证图片的获取
@register_blue.route("/image_code")
def get_image_code():
    img_code_id = request.args.get("image_code_id")
    if not img_code_id:
        abort(403)
    # 生成验证码
    img_text, img_bytes = generate_captcha_image()
    try:
        sr.set("img_code_id" + img_code_id, img_text, ex=180)
    except BaseException as e:
        current_app.logger.error(e)
        return abort(500)
    # 返回图片 设置自定义响应头Content-type
    response = make_response(img_bytes)  # type: Response
    response.content_type = "image/jpeg"

    return response


# 2.手机验证码的发送
@register_blue.route("/sms_code", methods=['POST'])
def get_sms_code():
    mobile = request.json.get("mobile")
    image_code = request.json.get("image_code")
    image_code_id = request.json.get("image_code_id")
    if not all([mobile, image_code, image_code_id]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 手机的格式是否正确
    if not re.match(r"1[35678]\d{9}$", mobile):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 根据取图片校验是否填写正确
    try:
        true_img_code = sr.get("img_code_id" + image_code_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg=error_map[RET.DATAERR])
    if not true_img_code:
        return jsonify(errno=RET.PARAMERR, errmsg="验证码过期")
    # 判断是否相同
    if true_img_code != image_code.upper():
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
    # 判断用户是否已经存在
    try:
        user = User.query.filter_by(mobile=mobile).first()
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg=error_map[RET.DATAERR])
    if user:
        return jsonify(errno=RET.DATAEXIST, errmsg=error_map[RET.DATAEXIST])

    # 发送短信-> 有一个第三方的库进行使用可以帮助我们发送
    sms_code = "%04d" % random.randint(0, 9999)
    current_app.logger.info("短信验证码为：%s" % sms_code)
    # response_code = CCP().send_template_sms('18500352930', [sms_code, 5], 1)
    # if response_code != 0:
    #     return jsonify(errno=RET.THIRDERR, errmsg=error_map[RET.THIRDERR])
    # 保存短信验证码  redis
    try:
        sr.set("sms_code_id" + mobile, sms_code, ex=60)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])
    # 返回json形式响应
    return jsonify(errno=RET.OK, errmsg=sms_code)


# 3.用户注册的实现
@register_blue.route("/register",methods=["POST"])
def register():
    mobile = request.json.get("mobile")
    sms_code = request.json.get("sms_code")
    password = request.json.get("password")
    # 校验参数
    if not all([mobile,sms_code,password]):
        return jsonify(errno= RET.PARAMERR,errmsg = error_map[RET.PARAMERR])
    # 手机的格式是否正确
    if not re.match(r"1[35678]\d{9}$", mobile):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
    # 校验验证码
    try:
        real_sms_code =  sr.get("sms_code_id" + mobile)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])
    if not real_sms_code:
        return jsonify(errno = RET.PARAMERR,errmsg = "验证码失效")
    if real_sms_code != sms_code:
        return jsonify(errno = RET.PARAMERR,errmsg = "验证码不正确")
    # 数据校验通过开始保存用户
    user = User()
    user.mobile = mobile
    user.password = password
    user.nick_name = mobile
    user.last_login = datetime.now()
    try:
        db.session.add(user)
        db.session.commit()
    except BaseException as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DATAERR,errmsg =error_map[RET.DATAERR])
    session["user_id"] = user.id
    return jsonify(errno=RET.OK, errmsg=sms_code)


# 4.用户登录
@register_blue.route("/login",methods = ["POST"])
def login():
    mobile = request.json.get("mobile")
    password = request.json.get("password")

    if not all([mobile,password]):
        return jsonify(errno = RET.PARAMERR,errmsg = error_map[RET.PARAMERR])

    # 手机的格式是否正确
    if not re.match(r"1[35678]\d{9}$", mobile):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    try:
        user = User.query.filter_by(mobile = mobile).first()
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DATAERR,errmsg = error_map[RET.DATAERR])
    if not user:
        return jsonify(errno = RET.USERERR,errmsg= error_map[RET.USERERR])

    if not user.check_password(password):
        return jsonify(errno = RET.PARAMERR,errmsg="密码有误")

    user.last_login = datetime.now()
    session["user_id"] = user.id
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])


# 5.退出登录
@register_blue.route("/logout")
def login_out():
    session.pop("user_id",None)
    session.pop("is_admin",None)
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])